package com.ticket.system.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import com.ticket.common.exception.base.BaseException;
import com.ticket.common.utils.Const;
import com.ticket.common.utils.DateUtils;
import com.ticket.common.utils.poi.ExcelUtil;
import com.ticket.system.domain.YanchuMovieCard;
import com.ticket.system.domain.vo.BatchExportVO;
import com.ticket.system.domain.vo.CardExportVO;
import com.ticket.system.mapper.YanchuMovieCardMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ticket.system.mapper.YanchuMovieBatchMapper;
import com.ticket.system.domain.YanchuMovieBatch;
import com.ticket.system.service.IYanchuMovieBatchService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;

/**
 * 观演卡批次信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-12-07
 */
@Service
public class YanchuMovieBatchServiceImpl implements IYanchuMovieBatchService 
{
    @Autowired
    private YanchuMovieBatchMapper yanchuMovieBatchMapper;
    @Autowired
    private YanchuMovieCardMapper yanchuMovieCardMapper;

    /**
     * 查询观演卡批次信息
     * 
     * @param id 观演卡批次信息主键
     * @return 观演卡批次信息
     */
    @Override
    public YanchuMovieBatch selectYanchuMovieBatchById(Long id)
    {
        YanchuMovieBatch movieBatch = yanchuMovieBatchMapper.selectYanchuMovieBatchById(id);
        if (null != movieBatch && Const.ONE.equals(movieBatch.getStatus())){
            YanchuMovieCard card = new YanchuMovieCard();
            card.setBatchId(id);
            List<YanchuMovieCard> cards = yanchuMovieCardMapper.selectYanchuMovieCardList(card);
            if (!CollectionUtils.isEmpty(cards)){
                YanchuMovieCard movieCard = cards.get(0);
                movieBatch.setActiveName(movieCard.getActiveName());
                movieBatch.setActiveTime(movieCard.getActiveTime());
                movieBatch.setActiveId(cards.get(0).getActiveId());
            }
        }
        return movieBatch;
    }

    /**
     * 查询观演卡批次信息列表
     * 
     * @param yanchuMovieBatch 观演卡批次信息
     * @return 观演卡批次信息
     */
    @Override
    public List<YanchuMovieBatch> selectYanchuMovieBatchList(YanchuMovieBatch yanchuMovieBatch)
    {
        return yanchuMovieBatchMapper.selectYanchuMovieBatchList(yanchuMovieBatch);
    }

    /**
     * 新增观演卡批次信息
     * 
     * @param yanchuMovieBatch 观演卡批次信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int insertYanchuMovieBatch(YanchuMovieBatch yanchuMovieBatch)
    {
        yanchuMovieBatch.setCreatTime(new Date());
        String batchName = yanchuMovieBatch.getBatchName();
        Integer creatNum = yanchuMovieBatch.getCreatNum();
        yanchuMovieBatchMapper.insertYanchuMovieBatch(yanchuMovieBatch);
        //生成观演卡号
        DecimalFormat format = new DecimalFormat("0000");
        List<YanchuMovieCard> cards = Lists.newArrayList();
        for (Integer integer = 1; integer <= creatNum; integer++) {
            YanchuMovieCard card = new YanchuMovieCard();
            String num = format.format(integer);
            card.setBatchId(yanchuMovieBatch.getId());
            card.setCardNum(batchName.concat(String.valueOf((int)((Math.random()*9+1)*1))).concat(num));
            card.setCardPasswoed(String.valueOf((int)((Math.random()*9+1)*100000)));
            card.setAmount(yanchuMovieBatch.getAmount());
            card.setBalance(new BigDecimal(yanchuMovieBatch.getAmount()));
            card.setCreatId(yanchuMovieBatch.getCreatId());
            card.setCreatName(yanchuMovieBatch.getCreatName());
            card.setCreatTime(new Date());
            card.setStatus(0);
            card.setValidTime(yanchuMovieBatch.getValidTime());
            cards.add(card);
        }
        //批量新增卡详情表
        return yanchuMovieCardMapper.insertYanchuMovieCards(cards);
    }

    /**
     * 修改观演卡批次信息
     * 
     * @param yanchuMovieBatch 观演卡批次信息
     * @return 结果
     */
    @Override
    public int updateYanchuMovieBatch(YanchuMovieBatch yanchuMovieBatch)
    {
        return yanchuMovieBatchMapper.updateYanchuMovieBatch(yanchuMovieBatch);
    }

    /**
     * 批量删除观演卡批次信息
     * 
     * @param ids 需要删除的观演卡批次信息主键
     * @return 结果
     */
    @Override
    public int deleteYanchuMovieBatchByIds(Long[] ids)
    {
        return yanchuMovieBatchMapper.deleteYanchuMovieBatchByIds(ids);
    }

    /**
     * 删除观演卡批次信息信息
     * 
     * @param id 观演卡批次信息主键
     * @return 结果
     */
    @Override
    public int deleteYanchuMovieBatchById(Long id)
    {
        return yanchuMovieBatchMapper.deleteYanchuMovieBatchById(id);
    }

    /**
     * 获取观演卡名称
     *
     * @return
     */
    @Override
    public String getCardName() {
        String time = DateUtils.dateTime();
        DecimalFormat format = new DecimalFormat("000");
        String oldBatchName = yanchuMovieBatchMapper.getCardName(time);
        int i = 1;
        if (StringUtils.isNotEmpty(oldBatchName)){
            String substring = oldBatchName.substring(9, 11);
            i = Integer.parseInt(substring) + 1;
        }
        return time.concat(format.format(i));
    }

    /**
     * 设置有效期
     *
     * @param batchIds
     * @param cardIds
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateValidTime(String batchIds, String cardIds,Date time) {
        if (StringUtils.isNotEmpty(batchIds)){
            //修改整个批次
            List<Long> ids = Arrays.stream(batchIds.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
            yanchuMovieBatchMapper.updateYanchuMovieBatchByIds(ids,time);
            yanchuMovieCardMapper.updateValidTimeByBatchIds(ids,time);
        }else {
            //修改单个卡
            List<Long> ids = Arrays.stream(cardIds.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
            yanchuMovieCardMapper.updateValidTimeByCardIds(ids,time);
        }
    }

    /**
     * 批次激活
     *
     * @param batchIds
     * @param activeId
     * @param activeName
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void activeBatch(String batchIds,Long activeId,String activeName) {
        List<Long> ids = Arrays.stream(batchIds.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        yanchuMovieBatchMapper.updateActiveByIds(ids);
        //添加激活人信息
        yanchuMovieCardMapper.updateActiveByBatchId(ids,activeId,activeName,new Date());
    }

    /**
     * 批量导出
     *
     * @param batchIds
     * @param response
     */
    @Override
    public void export(List<Long> batchIds, HttpServletResponse response){
        if (CollectionUtils.isEmpty(batchIds)){
            throw new BaseException("不存在批次");
        }
        List<BatchExportVO> vos = yanchuMovieBatchMapper.selectBatchByIds(batchIds);
        //生成表头
        List<String> headExcel = new ArrayList<>();
        headExcel.add("卡号");
        headExcel.add("卡面金额");
        headExcel.add("密码(加涂层)");
        HSSFWorkbook wb = new HSSFWorkbook();
        //标题设置样式
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 10);            // 字体高度
        font.setColor(HSSFFont.COLOR_NORMAL);                // 字体颜色
        font.setBold(true);  //加粗
        cellStyle.setFont(font);

        //表头设置样式
        HSSFCellStyle cellStyle1 = wb.createCellStyle();
        cellStyle1.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont font1 = wb.createFont();
        font1.setFontHeightInPoints((short) 10);            // 字体高度
        font1.setColor(HSSFFont.COLOR_NORMAL);                // 字体颜色
        cellStyle1.setFont(font);

        for (int i = 0; i < vos.size(); i++) {
            String sheetName = vos.get(i).getBatchName();
            HSSFSheet sheet = wb.createSheet(sheetName);
            sheet.setColumnWidth(0,23*256);
            //设置标题
            CellRangeAddress callRangeAddress = new CellRangeAddress(0, 0, 0, 2);//起始行,结束行,起始列,结束列
            //加载合并单元格
            sheet.addMergedRegion(callRangeAddress);
            Row row = sheet.createRow(0);
            Cell cell = row.createCell(0);
            cell.setCellValue("观演卡制卡数据");
            cell.setCellStyle(cellStyle);
            //设置表头
            Row row1 = sheet.createRow(1);
            for (int i1 = 0; i1 < headExcel.size(); i1++) {
                Cell cell1 = row1.createCell(i1);
                cell1.setCellValue(headExcel.get(i1));
                cell1.setCellStyle(cellStyle1);
            }
            List<CardExportVO> cards = vos.get(i).getVos();
            if (!CollectionUtils.isEmpty(cards)){
                for (int j = 0; j < cards.size(); j++) {
                    Row row2 = sheet.createRow(j+2);
                    Cell cell1 = row2.createCell(0);
                    cell1.setCellValue(cards.get(j).getCardNum());
                    Cell cell2 = row2.createCell(1);
                    cell2.setCellValue(cards.get(j).getAmount().concat("元"));
                    Cell cell3 = row2.createCell(2);
                    cell3.setCellValue(cards.get(j).getCardPasswoed());
                }
            }
        }
        ExcelUtil.exportExcel2Browser(response,"观演卡数据.xls",wb);
    }
}
